<?php
declare (strict_types=1);

namespace app\index\controller;

use app\BaseController;
use app\common\model\CommonBase;
use think\exception\HttpResponseException;
use think\facade\View;
use think\captcha\facade\Captcha;

class IndexBase extends BaseController
{
    protected const _LANGUAGE_COOKIE_KEY      = 'lang';
    protected const _WEBSITE_CODE_SESSION_KEY = 'website';
    protected $_websiteCode   = '';
    protected $_websiteConfig = [];
    protected $cdnDomain      = '';

    protected function initialize()
    {
        parent::initialize();
        $this->_initWebsite();
    }

    private function _initWebsite()
    {
        if (!file_exists('../install.lock')) {
            return $this->redirect((string)url('install/index/index'));
        }

        View::assign(['isHome' => false]);

        // 获取站点标识
        $lang        = $this->_getLange();
        $websiteCode = $this->_getWebsiteCode($lang);
        if (empty($websiteCode)) {
            return $this->redirect((string)url('platform/index/index'));
        }

        session(self::_WEBSITE_CODE_SESSION_KEY, $websiteCode);
        $this->_websiteCode = $websiteCode;

        // 获取站点配置
        $websiteConfigBusiness = new \app\common\business\WebsiteConfig($websiteCode);
        $websiteConfig         = $websiteConfigBusiness->getWebsiteConfigInfo($this->cdnDomain);
        $this->_websiteConfig  = $websiteConfig;
        View::assign(['config' => $websiteConfig]);

        // 校验站点状态
        $websiteStatus = $this->_checkWebsiteStatus($websiteCode);
        $noAuth        = !strstr($this->request->pathinfo(), "permission");
        if (!$websiteStatus && $noAuth) {
            $this->redirect((string)url('/permission/closed'));
        }
    }

    protected function _checkWebsiteStatus(string $websiteCode): bool
    {
        $websiteBusiness = new \app\common\business\Website();
        $websites        = $websiteBusiness->getAllWebsite();
        if (empty($websites)) {
            return false;
        }

        $website = $websites[$websiteCode] ?? [];
        if (empty($website)) {
            return false;
        }

        $this->cdnDomain = $website['cdn_domain'];

        return $website['status'] == CommonBase::IS_ENABLE_STATUS;
    }

    private function _getWebsiteCode($lang = ''): string
    {
        $code = env('website.' . str_replace('.', '_', $_SERVER['HTTP_HOST']));
        if (empty($code)) {
            return '';
        }

        $languages       = explode(',', env('website_' . $code . '.lang'));
        $lang            = in_array($lang, $languages) ? $lang : '';
        $defaultLanguage = strlen($lang) > 0 ? $lang : env('website_' . $code . '.default_lang');
        cookie(self::_LANGUAGE_COOKIE_KEY, $defaultLanguage);
        return $code . '_' . $defaultLanguage;
    }

    private function _getLange(): string
    {
        $lang = $this->request->param('lang', '', 'trim');
        if (!$lang) {
            $lang = (string)cookie(self::_LANGUAGE_COOKIE_KEY);
        }

        return $lang;
    }

    protected function _getWebsiteMetaInfo(): array
    {
        return [
            'metaTitle'       => $this->_websiteConfig['title'] ?? '',
            'metaKeyword'     => $this->_websiteConfig['meta_keyword'] ?? '',
            'metaDescription' => $this->_websiteConfig['meta_description'] ?? '',
        ];
    }

    public function redirect(...$args)
    {
        throw new HttpResponseException(redirect(...$args));
    }
}
